import * as Matter from 'matter-js';
import * as PIXI from "pixi.js";
import { gsap } from "gsap";
import { PixiPlugin } from "gsap/PixiPlugin";
import { Loader } from "./Loader";
import { ScenesManager } from "./ScenesManager";
import { Toast } from "antd-mobile";

class Application {
  run(config, handler) {
    PIXI.settings.TARGET_FPMS = 1 / 60;
    gsap.registerPlugin(PixiPlugin);
    PixiPlugin.registerPIXI(PIXI);

    this.config = config;

    Toast.show({content: `资源加载中`, duration: 0, maskClickable: false});

    this.gameDiv = document.getElementById('game');
    this.gameRender = document.getElementById('game-render');

    this.app = new PIXI.Application({
      resizeTo: this.gameDiv,
      resolution: window.devicePixelRatio,
      autoDensity: true,
      backgroundAlpha: 0
    });
    // alert(PIXI.Ticker.shared.FPS, this.app.ticker.FPS)
    this.app.ticker.maxFPS = 60;
    // alert(PIXI.Ticker.shared.FPS, this.app.ticker.FPS)
    this.gameDiv.appendChild(this.app.view);

    this.loader = new Loader(this.app.loader, this.config);
    this.loader.preload().then(() => {
      console.log("onComplete");
      Toast.clear();
      this.start()
    });

    // this.loader.onComplete.add(() => {
    //   console.log("onComplete");
    // })

    this.scenes = new ScenesManager();
    this.app.stage.interactive = true;
    this.app.stage.addChild(this.scenes.container);

    this.handler = handler;

    // [06]
    this.createPhysics();
  }

  createPhysics() {
    this.physics = Matter.Engine.create();

    this.physics.gravity.y = 2;

    // const render = Matter.Render.create({
    //   element: this.gameRender,
    //   engine: this.physics,
    //   options: {
    //     width: window.innerWidth,
    //     height: window.innerHeight,
    //     showAngleIndicator: true,
    //     wireframes: false
    //   }
    // });
    //
    // Matter.Render.run(render);

    const runner = Matter.Runner.create({isFixed: true, });
    // 锁定帧率
    runner.delta = 1000 / 60;
    // alert(runner.fps);
    // Matter.Events.on(runner, 'tick',() => {
    //   runner.delta = runner.fps > 60 ? 1000 / runner.fps : 1000 / 60;
    // })
    Matter.Runner.run(runner, this.physics);
  }

  // [/06]

  res(key) {
    return this.loader.resources[key].texture;
  }

  sprite(key) {
    return new PIXI.Sprite(this.res(key));
  }

  start() {
    this.scenes.start("Game");
  }
}

export const App = new Application();
